/**
 * Created by gongxun on 16/12/1.
 */

var GameAssetsManagerLoaderScene = cc.Scene.extend({
    ccsNode : null,
    Panel_touch : null,
    Text_tishi : null,
    Image_buttom : null,
    Image_loadingBg : null,
    Image_loadingItem : null,
    Fnt_text : null,

    //更新相关
    mAssetsManager : null,
    _percent : 1,
    _percentByFile : null,

    //更新完毕后
    _enterTime : null,

    //更新完毕后延迟加载
    _updatedEnterTime : null,

    //地址
    mainfestRess : null,
    //地址对应的url
    ressForUrl : null,
    //当前选择的地址
    resIndex : null,

    ctor : function(){
        this._super();
        this._updatedEnterTime = 0.0;

        this.mainfestRess = [
            "res/projectGame.manifest",
            "res/projectGame1.manifest"
        ];

        this.ressForUrl = [
            "http://qxkwx.oss-cn-beijing.aliyuncs.com/testGame",
            "http://qxkwx.oss-cn-beijing.aliyuncs.com/testGame1"
        ];
    },

    fixIosText:function(root) {
        if (root) {
            if (root.getName().substr(0, 5) === "Text_") {
                root.ignoreContentAdaptWithSize(true);
            }
            var arrayRootChildren = root.getChildren();
            var length = arrayRootChildren.length;
            for (var i = 0; i < length; i++) {
                var child = arrayRootChildren[i];
                this.fixIosText(child);
            }
        }
    },

    onExit:function(){
        if (this.mAssetsManager){
            this.mAssetsManager.release();
        }
        this._super();
    },

    loadUI : function(){
        //加载ccs
        var json = ccs.load("res/ccs/KwxUpdateLayer.json");
        this.ccsNode = json.node;
        this.addChild(this.ccsNode);
        var Panel_center = ccui.helper.seekWidgetByName(this.ccsNode, "Panel");
        Panel_center.setContentSize(mo.curSize.x, mo.curSize.y);
        ccui.helper.doLayout(Panel_center);
        this.fixIosText(this.ccsNode);

        //按钮
        this.Text_tishi = ccui.helper.seekWidgetByName(this.ccsNode, "Text_tishi");

        this.Panel_touch = ccui.helper.seekWidgetByName(this.ccsNode, "Panel_touch");
        this.Panel_touch.setTouchEnabled(false);

        this.Image_buttom = ccui.helper.seekWidgetByName(this.ccsNode, "Image_buttom");
        this.Image_buttom.setVisible(false);

        //更新相关
        this.Image_loadingBg = ccui.helper.seekWidgetByName(this.ccsNode, "Image_loadingBg");
        this.Image_loadingItem = ccui.helper.seekWidgetByName(this.ccsNode, "Image_loadingItem");
        this.Fnt_text = ccui.helper.seekWidgetByName(this.ccsNode, "Fnt_text");

        //重新更新
        this.Panel_touch.addTouchEventListener(function(sender, type){
            if (type == ccui.Widget.TOUCH_ENDED) {
                mo.gameAssetsManager();
            }
        }, this);

        this.setTishiContent("连接服务器...");

        this.showUpdateProgress(false);
    },

    run : function(resIndex){
        this.resIndex = resIndex;
        var mainfestRes = this.mainfestRess[resIndex];
        this.setLocalFileForIndex(resIndex);

        //TODO
        mainfestRes = "res/projectGame.manifest";

        var storagePath = (jsb.fileUtils ? jsb.fileUtils.getWritablePath() : "/");
        this.mAssetsManager = new jsb.AssetsManager(mainfestRes, storagePath);
        this.mAssetsManager.retain();

        // var localStoragePath = this.mAssetsManager.getStoragePath();

        this.loadUI();

        if (!this.mAssetsManager.getLocalManifest().isLoaded())
        {
            cc.log("Fail to update assets, step skipped.");
            this.loadGame();
        }
        else
        {
            var that = this;
            var listener = new jsb.EventListenerAssetsManager(this.mAssetsManager, function(event) {
                var code = event.getEventCode();
                // console.log("assets manager code:" + code);
                switch (code){
                    case jsb.EventAssetsManager.NEW_VERSION_FOUND:
                        //3 发现了新版本
                        that.onFoundNewVersion();
                        break;

                    case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
                        //4 已经是最新版本
                        that.loadGame();
                        break;

                    case jsb.EventAssetsManager.UPDATE_FINISHED:
                        //8 更新完成
                        that.loadGame();
                        break;

                    case jsb.EventAssetsManager.UPDATE_PROGRESSION:
                        //5 更新中
                        that._percent = event.getPercent();
                        that._percentByFile = event.getPercentByFile();
                        // cc.log("percent:" + that._percent);
                        break;

                    case 11:
                        //11 解压中
                        // cc.log("解压中");
                        that._percent = event.getPercent();
                        // cc.log("解压 percent:" + that._percent);
                        break;

                    case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
                        //0 没有找到本地manifest文件
                        that.onUpdateFail(code);
                        break;

                    case jsb.EventAssetsManager.ASSET_UPDATED:
                        //6 解压下载的文件
                        // cc.log("解压");
                        break;

                    case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
                        //1 没有找到服务器上的manifest文件
                        that.onUpdateFail(code);
                        break;

                    case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
                        //2 服务器上的manifest文件解析失败
                        that.onUpdateFail(code);
                        break;

                    case jsb.EventAssetsManager.ERROR_UPDATING:
                        //7 更新中的失败
                        that.onUpdateFail(code);
                        break;

                    case jsb.EventAssetsManager.UPDATE_FAILED:
                        //9 更新失败
                        that.onUpdateFail(code);
                        break;

                    case jsb.EventAssetsManager.ERROR_DECOMPRESS:
                        //10 解压缩失败
                        that.onUpdateFail(code);
                        break;

                    default:
                        break;
                }
            });

            cc.eventManager.addListener(listener, 1);
            // this.mAssetsManager.checkUpdate();
            this.onStartUpdate();
            cc.director.runScene(this);
        }
    },

    updateProgress:function(dt){
        this.setUpdateProgress(this._percent);
    },

    //发现新版本
    onFoundNewVersion : function(){
        this._updatedEnterTime = 0.5;

        this.setTishiContent("发现新版本，点击屏幕更新");

        this.Image_buttom.setVisible(false);
        this.showUpdateProgress(true);
    },

    //开始更新
    onStartUpdate : function(){
        this.mAssetsManager.update();
        this.schedule(this.updateProgress, 0.1);
        this.Image_buttom.setVisible(true);
    },

    //更新失败
    onUpdateFail : function(code){
        cc.log("update for cdn errors... code : " + code);

        //关闭定时器
        this.unschedule(this.updateProgress);
        //显示底部
        this.Image_buttom.setVisible(true);
        //关闭进度显示
        this.showUpdateProgress(false);

        if (code == 7 || code == 9 || code == 1){
            this.setTishiContent("连接服务器失败，请检查网络 错误代码:" + code + "(点击屏幕重试)");
        }else{
            this.setTishiContent("更新失败，请稍后再试 错误代码:" + code + "(点击屏幕重试)");
        }

        this.Panel_touch.setTouchEnabled(true);

        if (code == 1){
            //没有取到服务器上的配置文件
            //准备切换了
            // if (this.resIndex == 0){
            //     mo.gameAssetsManager1();
            // }

            // mo.assetsUpdateErrorCount++;
            //
            // if (mo.assetsUpdateErrorCount >= 5){
            //     //没有找到文件的情况允许
            //     this.loadGame();
            //     return;
            // }
        }
    },

    //写本地文件对应不同ip
    setLocalFileForIndex : function(index){
        //TODO
        return;
        var url = this.ressForUrl[index];

        //首先读取文件
        var writeblePath = jsb.fileUtils.getWritablePath();

        var changeFile = function(file){
            var writeFullPath = writeblePath + file;
            var str = jsb.fileUtils.getStringFromFile(writeFullPath);

            if (str == ""){
                cc.log(file + "为空...");
                return;
            }

            //分别保存
            var json = JSON.parse(str);
            json.packageUrl = url;
            json.remoteManifestUrl = url + "/project.manifest";
            json.remoteVersionUrl = url + "/version.manifest";

            jsb.fileUtils.writeStringToFile(JSON.stringify(json), writeFullPath);
        };

        changeFile("project.manifest");
        changeFile("version.manifest");
    },

    //显示提示信息
    setTishiContent : function(content){
        this.Text_tishi.setString(content);
        this.Text_tishi.setContentSize(this.Text_tishi.getAutoRenderSize());
        this.Text_tishi.setTextColor(cc.color(255, 255, 255));
    },

    //更新更新进度
    setUpdateProgress : function(percent){
        var fntStr = percent.toFixed(0) + "%";
        this.Fnt_text.setString(fntStr);

        var maxx = 795;
        var minx = 100;
        var size = cc.size(percent / 100 * (maxx - minx) + 100, 41);
        this.Image_loadingItem.setContentSize(size);
    },

    //是否显示进度条
    showUpdateProgress : function(isShow){
        this.Image_loadingBg.setVisible(isShow);
    },

    loadGame : function(){
        //TODO
        this._percent = 100.0;
        this.setUpdateProgress(100.0);
        this.scheduleOnce(function(dt){
            mo.gameVersion.start();
        }, this._updatedEnterTime);

        // cc.log("_updatedEnterTime:" + this._updatedEnterTime);
        return;

        //加载通用js
        //动画完毕后再进入界面
        var animTime = 1.0;
        this._enterTime = 0.5;
        this.schedule(function(dt){
            this._enterTime += (dt / 2);
            var percent = this._enterTime / animTime;
            percent *= 100.0;
            if (percent > 100){
                percent = 100;
            }
            this.setUpdateProgress(percent);
        });
        this.scheduleOnce(function(dt){
            mo.gameVersion.start();
        }, 0.5);
    }
});

var mo = mo || {};

mo.gameAssetsManager = function(){
    new GameAssetsManagerLoaderScene().run(0);
};

mo.gameAssetsManager1 = function(){
    new GameAssetsManagerLoaderScene().run(1);
};

mo.assetsUpdateErrorCount = 0;